package com.qiall.bashutil;

import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.eclipse.jgit.transport.CredentialsProvider;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;

import java.io.IOException;
import java.nio.file.Paths;

/**
 *  Git git = jGitUtils.openRpo(localPath); 获取git对象
 *  Git git = Git.init().setDirectory(new File(localPath)).call(); init git 对象
 *
 */
//https://blog.csdn.net/qq_44299928/article/details/109577937
public class GitScripUtil {

    /**
     * 获取git 对象
     * @param dir
     * @return
     */
    public static Git openRpo(String dir) {
        Git git = null;
        try {
            Repository repository = new FileRepositoryBuilder()
                    .setGitDir(Paths.get(dir, ".git").toFile())
                    .build();
            git = new Git(repository);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return git;
    }

    public static boolean pull(String userName,String password,String respLocation,String branch){
        CredentialsProvider provider = new UsernamePasswordCredentialsProvider(userName, password);  //生成身份信息
       Git git= openRpo(respLocation);
        try {
            git.pull()
                    .setRemoteBranchName(branch)  //设置需要pull的远端分支
                    .setCredentialsProvider(provider)  //身份验证
                    .call();
        } catch (GitAPIException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 检出分支
     * @param respLocation
     * @param branch
     */
    public static void checkOut(String respLocation,String branch){
        Git git= openRpo(respLocation);
        try {
            git.checkout()
                    .setName(branch) //设置分支名
                    .call();
        } catch (GitAPIException e) {
            e.printStackTrace();
        }
    }

}


